# -*- coding: utf-8 -*-

import urllib2
import urllib
import re

def auto_login(email, passwd):
    pass

def get_user_cookie(uid):
    """
    Get 'remember me' cookie values
    """
    return 'bid=wu0CVRUFKuw;dbcl2=50773728:qBpwXqD91nM;ck=00WS'

def get_unread_mail(uid):
    """
    Get user's all unread mails
    TODO:paginate
    """
    cookie = get_user_cookie(uid)
    if cookie is None:
        return None
    req = urllib2.Request("http://www.douban.com/doumail/unread")
    #req = urllib2.Request("http://www.douban.com/doumail")
    req.add_header('Cookie', cookie)
    html = urllib2.urlopen(req).read()

    h=re.findall(r'table class="olt".*?\<\/table\>',html,re.M|re.S)

    if len(h) == 0:
        print 'Extract html content is None'
        return None

    mail_list = re.findall(r'\<div class="doumail_from"><a href="(http://www.douban.com/people.*?)"\>(.*?)<\/a>.*?<a href="(http://www.douban.com/doumail.*?)">.*?\<td>(.*?)\<\/td\>.*?\<\/tr\>',h[0],re.M|re.S)
    # mail_list (people_url, people_name, doumail_href, date)
    
    if mail_list is None or len(mail_list) == 0:
        print 'Extracted mail_list is None.'
        return None

    ret = []
    
    for mail in mail_list:
        mail = {'people':{'id':mail[0],'name':mail[1]}, 'mail':{'id':mail[2],'date':mail[3]} }       
        ret.append(mail)

    return ret
    


def get_mail_content(mail_id, uid):
    """
    Get the specified mail content
    """
    cookie = get_user_cookie(uid)
    if cookie is None:
        return None
    req = urllib2.Request(mail_id)
    req.add_header('Cookie', cookie)
    html = urllib2.urlopen(req).read()
    
    if html is None or len(html) == 0:
        return None

    m = re.findall(r'\<div class="doumail-body".*?\<span class="pl2">.*?(\d{4}-\d{2}-\d{2} \d{2}:\d{2})</span>.*?<span class="m">(.*?)</span></div>(.*?)<div class="ul">.*?name="m_reply"',html,re.M|re.S)

    if m and len(m) > 0:
        ret = {'title':m[0][1],'content':m[0][2],'time':m[0][0]}
        return ret

    return None

def send_mail(sender_id, receiver_id, title, content, ck):
    data = {'ck':ck, 'to':receiver_id, 'm_subject':title.encode('utf-8'), 'm_text':content.encode('utf-8'), 'm_submit':'submit'}

    cookie = get_user_cookie(sender_id)
    if cookie is None:
        return None
    req = urllib2.Request("http://www.douban.com/doumail/write")
    req.add_header('Cookie', cookie)
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    encode_data = urllib.urlencode(data)
    print encode_data
    rep = urllib2.urlopen(req , encode_data).read()


def delete_mail(mail_id):
    pass

if __name__ == '__main__':
    mails = get_unread_mail('test')

    print len(mails)
    """
    for m in mails:
        print m
    content = get_mail_content(mails[0]["mail"]['id'], mails[0]['people']['id'])
    if content:
        print content
    else:
        print "Content is None."
    send_mail('50773728','51230448',u'中文','test content','WSiX')
    """
